package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.entity.User;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ReportMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;


@Service
public class ReportServiceImpl implements ReportService {
    @Autowired
    private WorkspaceService workspaceService;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;

    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverReportVOResult(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        TurnoverReportVO vo = new TurnoverReportVO();
        vo.setDateList(StringUtils.join(dateList,","));

        List<Double> turnovers = new ArrayList<>();
        for (LocalDate date:dateList){
            LocalDateTime begintime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endtime = LocalDateTime.of(date, LocalTime.MAX);
            Double turnover = orderMapper.getTurnover(begintime,endtime, Orders.COMPLETED);
            turnover = turnover==null? 0.0:turnover;
            turnovers.add(turnover);
        }
        vo.setTurnoverList(StringUtils.join(turnovers,","));
        return vo;
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userReportVOResult(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        UserReportVO vo = new UserReportVO();
        vo.setDateList(StringUtils.join(dateList,","));
        List<Long> newUsers = new ArrayList<>();
        int totalUser = 0;
        for (LocalDate date:dateList){
            LocalDateTime begintime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endtime = LocalDateTime.of(date, LocalTime.MAX);
            Long newuser = userMapper.getNewUser(begintime, endtime);
            newUsers.add(newuser);
            totalUser+=newuser;
        }
        vo.setNewUserList(StringUtils.join(newUsers,","));
        vo.setTotalUserList(String.valueOf(totalUser));
        return vo;
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        List<Number> voc = new ArrayList<>();
        List<Number> tol = new ArrayList<>();
        int totaloc=0;
        int validoc=0;
        for (LocalDate date:dateList){
            LocalDateTime begintime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endtime = LocalDateTime.of(date, LocalTime.MAX);
            Integer total = orderMapper.getall(begintime,endtime);
            Integer valid = orderMapper.getvalid(begintime,endtime,Orders.COMPLETED);
            totaloc+=total;
            validoc+=valid;
            voc.add(valid);
            tol.add(total);
        }
        OrderReportVO vo = new OrderReportVO();
        Double number = (double) (validoc/totaloc);
        vo.setDateList(StringUtils.join(dateList,','));
        vo.setOrderCompletionRate(number);
        vo.setTotalOrderCount(totaloc);
        vo.setValidOrderCount(validoc);
        vo.setOrderCountList(StringUtils.join(tol,','));
        vo.setValidOrderCountList(StringUtils.join(voc,','));
        return vo;
    }

    /**
     * 查询top10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        List<String> namelist = new ArrayList<>();
        List<Integer> numberlist = new ArrayList<>();
        LocalDateTime begintime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endtime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> list = orderMapper.top10(begintime,endtime,Orders.COMPLETED);
        for (GoodsSalesDTO dto:list){
            namelist.add(dto.getName());
            numberlist.add(dto.getNumber());
        }
        SalesTop10ReportVO vo = new SalesTop10ReportVO();
        vo.setNameList(StringUtils.join(namelist,','));
        vo.setNumberList(StringUtils.join(numberlist,','));
        return vo;
    }

    @Override
    public void export(HttpServletResponse response) {
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);

        BusinessDataVO vo = workspaceService.getBusinessData(LocalDateTime.of(begin,LocalTime.MIN),LocalDateTime.of(end,LocalTime.MIN));

        InputStream inputStream = null;
        try {
            inputStream = new FileInputStream("E:\\BaiduNetdiskDownload\\资料\\资料\\day12\\运营数据报表模板.xlsx");
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        try {
            XSSFWorkbook excel  = new XSSFWorkbook(inputStream);
            XSSFSheet sheet = excel.getSheet("Sheet1");

            //填充数据--时间
            sheet.getRow(1).getCell(1).setCellValue("时间：" + begin + "至" + end);

            //获得第4行
            XSSFRow row = sheet.getRow(3);
            row.getCell(2).setCellValue(vo.getTurnover());
            row.getCell(4).setCellValue(vo.getOrderCompletionRate());
            row.getCell(6).setCellValue(vo.getNewUsers());

            //获得第5行
            row = sheet.getRow(4);
            row.getCell(2).setCellValue(vo.getValidOrderCount());
            row.getCell(4).setCellValue(vo.getUnitPrice());

            //填充明细数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                //查询某一天的营业数据
                BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));

                //获得某一行
                row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData.getTurnover());
                row.getCell(3).setCellValue(businessData.getValidOrderCount());
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData.getUnitPrice());
                row.getCell(6).setCellValue(businessData.getNewUsers());
            }

            //3. 通过输出流将Excel文件下载到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            excel.write(out);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }
}
